// 在線用戶
let onlineUsers = {}
// 當前用戶人數
// let onlineCount = 0
let i = 0

module.exports = function (io) {
  // 连接socket.io
  io.on('connection', (socket) => {
    // TODO 处理上线
    socket.broadcast.emit('/access')
    socket.name = ++i
    onlineUsers[socket.name] = socket

    // TODO 接收消息
    socket.on('message', (msg) => {
      console.log(socket.name, 'name')
      io.emit('jieshou', msg)
    })

    // TODO 有人离开了
    socket.on('disconnect', () => {
      socket.broadcast.emit('/leave')
      delete onlineUsers[socket.name]
    })

    // TODO 修改昵称
    socket.on('/user/modify', (nickName) => {
      delete onlineUsers[socket.name]
      onlineUsers[nickName] = socket
      socket.emit('/curpeople', Object.keys(onlineUsers))
    })

    // TODO 获取当前人数
    socket.on('/user/list', (callback) => {
      // console.log(Object.keys(onlineUsers), 'onlineUsers')
      callback(Object.keys(onlineUsers).length)
    })

    // TODO 更新消息列表
    socket.on('/user/list/update', (id) => {
      socket.broadcast.emit('/update-list', id)
    })
  })
}
